<template>
  <div class="forum-management">
    <h2 class="page-title">论坛管理</h2>
    <el-tabs v-model="activeTab" @tab-click="debouncedHandleTabClick">
      <!-- 帖子管理 -->
      <el-tab-pane label="帖子管理" name="posts">
        <div class="toolbar">
          <el-input
              v-model="postSearchQuery"
              placeholder="输入标题或内容搜索"
              clearable
              style="width: 300px"
              @keyup.enter="fetchPosts"
          >
            <template #prepend>
              <el-button icon="Search" @click="fetchPosts" />
            </template>
          </el-input>
          <el-button
              type="danger"
              :disabled="!selectedPosts.length"
              :loading="batchDeletingPosts"
              @click="batchDeletePosts"
          >
            批量删除
          </el-button>
        </div>
        <el-table
            ref="postTable"
            :data="posts"
            style="width: 100%"
            @selection-change="handlePostSelectionChange"
            row-key="postId"
            border
            height="calc(100vh - 300px)"
            v-loading="loadingPosts"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="postId" label="帖子ID" width="80" sortable />
          <el-table-column prop="title" label="标题" width="200" show-overflow-tooltip />
          <el-table-column prop="content" label="内容" show-overflow-tooltip />
          <el-table-column prop="userId" label="用户ID" width="100" sortable />
          <el-table-column prop="createdAt" label="创建时间" width="160" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button
                  type="danger"
                  size="small"
                  :loading="deletingPostId === scope.row.postId"
                  @click="deletePost(scope.row.postId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            :current-page="postPagination.currentPage"
            :page-size="postPagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="postPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @update:current-page="postPagination.currentPage = $event; fetchPosts()"
            @update:page-size="postPagination.pageSize = $event; fetchPosts()"
            class="pagination"
        />
      </el-tab-pane>

      <!-- 评论管理 -->
      <el-tab-pane label="评论管理" name="comments">
        <div class="toolbar">
          <el-input
              v-model="commentSearchQuery"
              placeholder="输入评论内容搜索"
              clearable
              style="width: 300px"
              @keyup.enter="fetchComments"
          >
            <template #prepend>
              <el-button icon="Search" @click="fetchComments" />
            </template>
          </el-input>
          <el-button
              type="danger"
              :disabled="!selectedComments.length"
              :loading="batchDeletingComments"
              @click="batchDeleteComments"
          >
            批量删除
          </el-button>
        </div>
        <el-table
            ref="commentTable"
            :data="comments"
            style="width: 100%"
            @selection-change="handleCommentSelectionChange"
            row-key="commentId"
            border
            height="calc(100vh - 300px)"
            v-loading="loadingComments"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="commentId" label="评论ID" width="80" sortable />
          <el-table-column prop="content" label="内容" show-overflow-tooltip />
          <el-table-column prop="userId" label="用户ID" width="100" sortable />
          <el-table-column prop="postId" label="帖子ID" width="100" sortable />
          <el-table-column prop="createdAt" label="创建时间" width="160" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button
                  type="danger"
                  size="small"
                  :loading="deletingCommentId === scope.row.commentId"
                  @click="deleteComment(scope.row.commentId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            :current-page="commentPagination.currentPage"
            :page-size="commentPagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="commentPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @update:current-page="commentPagination.currentPage = $event; fetchComments()"
            @update:page-size="commentPagination.pageSize = $event; fetchComments()"
            class="pagination"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import axios from 'axios';
import { debounce } from 'lodash';

export default {
  name: 'ForumManagement',
  data() {
    return {
      activeTab: 'posts',
      posts: [],
      comments: [],
      postSearchQuery: '',
      commentSearchQuery: '',
      selectedPosts: [],
      selectedComments: [],
      postPagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0, // 初始值为 0，需后端返回总条数
      },
      commentPagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0, // 初始值为 0，需后端返回总条数
      },
      loadingPosts: false,
      loadingComments: false,
      deletingPostId: null,
      deletingCommentId: null,
      batchDeletingPosts: false,
      batchDeletingComments: false,
    };
  },
  created() {
    this.debouncedHandleTabClick = debounce(this.handleTabClick, 300);
  },
  mounted() {
    this.fetchPosts();
    this.fetchComments();
  },
  methods: {
    async fetchPosts() {
      this.loadingPosts = true;
      try {
        const response = await axios.get('/api/admin/posts', {
          headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
          params: {
            page: this.postPagination.currentPage,
            size: this.postPagination.pageSize,
            query: this.postSearchQuery,
          },
        });
        console.log('帖子数据:', response.data);
        // 直接使用返回的数组，临时通过数组长度推算总数
        this.posts = response.data || [];
        this.postPagination.total = response.data.length; // 临时方案，后端需返回 total
      } catch (error) {
        console.error('获取帖子失败:', error);
        this.$message.error('获取帖子列表失败，请检查网络或权限');
      } finally {
        this.loadingPosts = false;
      }
    },
    async fetchComments() {
      this.loadingComments = true;
      try {
        const response = await axios.get('/api/admin/comments', {
          headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
          params: {
            page: this.commentPagination.currentPage,
            size: this.commentPagination.pageSize,
            query: this.commentSearchQuery,
          },
        });
        console.log('评论数据:', response.data);
        // 直接使用返回的数组，临时通过数组长度推算总数
        this.comments = response.data || [];
        this.commentPagination.total = response.data.length; // 临时方案，后端需返回 total
      } catch (error) {
        console.error('获取评论失败:', error);
        this.$message.error('获取评论列表失败，请检查网络或权限');
      } finally {
        this.loadingComments = false;
      }
    },
    async deletePost(postId) {
      this.$confirm('确定要删除此帖子吗？删除后不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        this.deletingPostId = postId;
        try {
          await axios.delete(`/api/admin/posts/${postId}`, {
            headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
          });
          this.$message.success('删除帖子成功');
          this.fetchPosts();
        } catch (error) {
          this.$message.error('删除帖子失败，请重试');
        } finally {
          this.deletingPostId = null;
        }
      });
    },
    async deleteComment(commentId) {
      this.$confirm('确定要删除此评论吗？删除后不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        this.deletingCommentId = commentId;
        try {
          await axios.delete(`/api/admin/comments/${commentId}`, {
            headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
          });
          this.$message.success('删除评论成功');
          this.fetchComments();
        } catch (error) {
          this.$message.error('删除评论失败，请重试');
        } finally {
          this.deletingCommentId = null;
        }
      });
    },
    async batchDeletePosts() {
      this.$confirm(`确定要删除 ${this.selectedPosts.length} 个选中的帖子吗？删除后不可恢复`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        this.batchDeletingPosts = true;
        try {
          await Promise.all(
              this.selectedPosts.map(postId =>
                  axios.delete(`/api/admin/posts/${postId}`, {
                    headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
                  })
              )
          );
          this.$message.success('批量删除帖子成功');
          this.fetchPosts();
        } catch (error) {
          this.$message.error('批量删除帖子失败，请重试');
        } finally {
          this.batchDeletingPosts = false;
        }
      });
    },
    async batchDeleteComments() {
      this.$confirm(`确定要删除 ${this.selectedComments.length} 个选中的评论吗？删除后不可恢复`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        this.batchDeletingComments = true;
        try {
          await Promise.all(
              this.selectedComments.map(commentId =>
                  axios.delete(`/api/admin/comments/${commentId}`, {
                    headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` },
                  })
              )
          );
          this.$message.success('批量删除评论成功');
          this.fetchComments();
        } catch (error) {
          this.$message.error('批量删除评论失败，请重试');
        } finally {
          this.batchDeletingComments = false;
        }
      });
    },
    handlePostSelectionChange(val) {
      this.selectedPosts = val.map(row => row.postId);
    },
    handleCommentSelectionChange(val) {
      this.selectedComments = val.map(row => row.commentId);
    },
    handleTabClick() {
      if (this.activeTab === 'posts') {
        this.fetchPosts();
      } else {
        this.fetchComments();
      }
    },
    formatDate(date) {
      return date ? new Date(date).toLocaleString('zh-CN', { hour12: false }) : '-';
    },
  },
};
</script>

<style scoped>
.forum-management {
  padding: 20px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  min-height: calc(100vh - 96px);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 24px;
  line-height: 1.2;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
  padding: 8px 0;
}

.el-table {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.el-table th {
  background-color: #f8fafc;
  color: #1f2937;
  font-weight: 600;
  padding: 12px 0;
}

.el-table td {
  color: #4b5563;
  padding: 10px 0;
}

.el-table .cell {
  word-break: break-word;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding: 12px 0;
}

.el-tabs {
  --el-tabs-header-height: 48px;
}

.el-tabs__item {
  font-size: 16px;
  font-weight: 500;
  padding: 0 20px;
  color: #4b5563;
}

.el-tabs__item.is-active {
  color: #3b82f6;
  font-weight: 600;
}

.el-tabs__active-bar {
  background-color: #3b82f6;
}

.el-button--danger {
  background-color: #ef4444;
  border-color: #ef4444;
  font-weight: 500;
}

.el-button--danger:hover {
  background-color: #dc2626;
  border-color: #dc2626;
}

.el-input__inner {
  border-radius: 6px;
}

.el-pagination {
  font-weight: 500;
}

.el-loading-mask {
  background-color: rgba(0, 0, 0, 0.05);
}
</style>